package com.et.machine.manager.vm.goods

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.Toast
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import com.et.machine.R
import com.et.machine.databinding.DialogAddGoodsInformationBinding
import com.et.machine.databinding.ItemAddGoodsInformationDialogBinding
import com.et.machine.goods.globalDiscountMap
import com.et.machine.store.ChannelEntity
import com.et.machine.store.DISABLED
import com.et.machine.store.ENABLED
import com.et.util.getFileExtensionFromUrl
import java.io.File
import java.math.BigDecimal
import java.util.regex.Pattern

@Suppress("DEPRECATION")
class GoodsInformationDialog(
    context: Context,
    private var list: MutableList<rows>,
    channelEntity: ChannelEntity,
    customDialogListener: OnDialogListener
) : Dialog(
    context, R.style.common_dialog
) {
    private lateinit var binding: DialogAddGoodsInformationBinding
    private lateinit var adapter: AdapterUseDiff<rows, ItemAddGoodsInformationDialogBinding>
    private var rows: rows? = null
    private var index: Int? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DialogAddGoodsInformationBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.ensure.setOnClickListener(ensureClickListener)
        binding.cancel.setOnClickListener(cancelClickListener)
        binding.enable.setOnClickListener(enableClickListener)



        binding.name.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                searchData(binding.name.text.toString())
            }

            override fun afterTextChanged(s: Editable?) {
            }

        })

        binding.price.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                val match =
                    Pattern.compile("^(([1-9]\\d*)|([0]))(\\.(\\d){0,2})?$").matcher(s.toString())
                if (!match.matches() || s.toString().toBigDecimal() > BigDecimal(99.99)) {
                    binding.price.setTextColor(Color.RED)
                    binding.ensure.setBackgroundColor(Color.GRAY)
                    binding.ensure.isClickable = false
                } else {
                    binding.price.setTextColor(Color.BLACK)
                    binding.ensure.setBackgroundColor(Color.parseColor("#26AAAA"))
                    binding.ensure.isClickable = true
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }

        })

        binding.barcode.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                searchBarcode(binding.barcode.text.toString())
            }

            override fun afterTextChanged(s: Editable?) {
            }

        })



        binding.recyclerview.layoutManager = LinearLayoutManager(context).apply {
            orientation = LinearLayoutManager.VERTICAL
        }
        adapter = AdapterUseDiff({ binding, _, rows ->
            binding.name.text = rows.name
            binding.barcode.text = rows.barcode
            val imageFile =
                File("${Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).absolutePath}/${rows.name}.${rows.image.getFileExtensionFromUrl()}")
            if (imageFile.exists()) {
                binding.image.setImageURI(Uri.fromFile(imageFile))
            } else {
                binding.image.setImageResource(R.mipmap.wu)
            }


            if (rows == this.rows) {
                binding.bg.setBackgroundColor(Color.GRAY)
            } else {
                binding.bg.setBackgroundColor(Color.WHITE)
            }
            binding.root.setOnClickListener {
                showInputTips(this.binding.price)
                binding.bg.setBackgroundColor(Color.GRAY)
                if (index != null && this.binding.recyclerview.getChildAdapterPosition(binding.root) != index) {
                    this.binding.recyclerview.findViewHolderForAdapterPosition(index!!)?.itemView?.setBackgroundColor(
                        Color.WHITE
                    )
                }
                this.rows = rows
                index = this.binding.recyclerview.getChildAdapterPosition(binding.root)
            }

        }, { layoutInflater: LayoutInflater, viewGroup: ViewGroup ->
            ItemAddGoodsInformationDialogBinding.inflate(layoutInflater, viewGroup, false)
        })
        adapter.data = list
        Log.d("rowsList size", list.size.toString())
        binding.recyclerview.adapter = adapter


    }

    private fun showInputTips(et_text: EditText) {
        et_text.isFocusable = true
        et_text.isFocusableInTouchMode = true
        et_text.requestFocus()
        val inputManager =
            et_text.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputManager.showSoftInput(et_text, 0)
    }

    //发送消息,回调函数取值;
    private val ensureClickListener = View.OnClickListener {
        if (rows != null && binding.price.text.toString().isNotEmpty()) {
            customDialogListener.back(channelEntity.apply {
                this.name = rows!!.name
                this.priceCent =
                    (binding.price.text.toString().toBigDecimal().multiply(BigDecimal(100)).toInt())
                this.image = rows!!.image
                this.status = ENABLED
                this.barcode = rows!!.barcode
                this.discount = globalDiscountMap[barcode] ?: 100
            })
            dismiss()
        } else {
            Toast.makeText(context, "请选择商品并输入价格", Toast.LENGTH_LONG).show()
        }
    }

    //取消发送;
    private val cancelClickListener = View.OnClickListener {
        dismiss() //关闭提示框
    }

    private val enableClickListener = View.OnClickListener {
        customDialogListener.back(channelEntity.apply {
            status = DISABLED
        })

        dismiss() //关闭提示框
    }

    interface OnDialogListener {
        fun back(channelEntity: ChannelEntity)
    }

    private fun searchData(word: String) {
        val showData: MutableList<rows> = mutableListOf()
        for (i in 0 until list.size) {
            if (list[i].firstName.contains(word) || list[i].pinYin.contains(word)) {
                showData.add(list[i])
            }
        }
        adapter.dispatchUpdate(
            DiffUtil.calculateDiff(
                RowsDiffCallBack(adapter.data, showData),
                true
            ), showData
        )
    }

    private fun searchBarcode(word: String) {
        val showData: MutableList<rows> = mutableListOf()
        for (i in 0 until list.size) {
            if (list[i].barcode.contains(word)) {
                showData.add(list[i])
            }
        }
        adapter.dispatchUpdate(
            DiffUtil.calculateDiff(
                RowsDiffCallBack(adapter.data, showData),
                true
            ), showData
        )
    }
}

class RowsDiffCallBack(
    private val src: MutableList<rows>,
    private val dest: MutableList<rows>
) :
    DiffUtil.Callback() {
    override fun getOldListSize(): Int = src.size

    override fun getNewListSize(): Int = dest.size

    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        if (oldItemPosition < src.size && newItemPosition < dest.size) {
            return TextUtils.equals(src[oldItemPosition].name, dest[newItemPosition].name)
        }
        return false
    }


    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        if (oldItemPosition < src.size && newItemPosition < dest.size) {
            val oldItem = src[oldItemPosition]
            val newItem = dest[newItemPosition]
            return TextUtils.equals(oldItem.name, newItem.name)
                    && TextUtils.equals(oldItem.barcode, newItem.barcode)
                    && oldItem.firstName == newItem.firstName
                    && oldItem.image == newItem.image
                    && oldItem.pinYin == newItem.pinYin
        }
        return false
    }

}